{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "10eebb1d",
   "metadata": {},
   "source": [
    "# Agentic Workflow: 感知—检索—推理—生成—反馈—自驱优化\n",
    "\n",
    "本Notebook演示一个多阶段智能体（Agent）架构，涵盖感知（Perception）、检索（Retrieval）、推理（Reasoning）、生成（Generation）、反馈（Feedback）、自驱优化（Self-Improvement）等环节。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ab811256",
   "metadata": {},
   "source": [
    "## 1. 感知（Perception）\n",
    "\n",
    "模拟Agent接收外部输入（如用户问题、环境数据等）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f94900f5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 感知：通过LLM理解用户输入意图（OpenAI API示例）\n",
    "import os\n",
    "import openai\n",
    "\n",
    "openai.api_key = os.getenv('OPENAI_API_KEY')\n",
    "\n",
    "raw_input = \"请简要介绍Transformer架构的核心思想。\"\n",
    "\n",
    "def perceive_intent(text):\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": \"你是一个智能体的感知模块，请识别用户输入的意图，并用一句话总结。\"},\n",
    "        {\"role\": \"user\", \"content\": text}\n",
    "    ]\n",
    "    response = openai.ChatCompletion.create(\n",
    "        model=\"gpt-3.5-turbo\",\n",
    "        messages=messages,\n",
    "        max_tokens=64\n",
    "    )\n",
    "    return response.choices[0].message.content.strip()\n",
    "\n",
    "user_input = perceive_intent(raw_input)\n",
    "print(\"感知到的用户意图：\", user_input)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f59d4d91",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 可选：若缺少依赖，请在具有写权限的环境中手工安装：\n",
    "# %pip install PyPDF2 python-docx beautifulsoup4 pandas PyYAML scikit-learn\n",
    "# 下面代码在缺包时会优雅降级。\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1754c54",
   "metadata": {},
   "source": [
    "### 感知+：文档智能感知流水线\n",
    "\n",
    "本节在感知层加入文档智能处理能力：\n",
    "- 自动识别文档类型与格式（PDF/DOCX/CSV/XLSX/JSON/YAML/HTML/TXT/MD）\n",
    "- 基于类型选择最优解析策略，抽取纯文本/结构化信息\n",
    "- 使用LLM与规则混合抽取关键字段（项目名称、预算、时间、负责人等）\n",
    "- 进行质量验证与清洗（数值/日期/货币标准化、缺失与一致性检查）\n",
    "- 将清洗后的结构化特征向量化，供后续检索/推理模块使用"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a641782b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 文档类型识别与解析策略选择\n",
    "from typing import Optional, Tuple\n",
    "import os, json, re\n",
    "\n",
    "try:\n",
    "    import yaml\n",
    "except Exception:\n",
    "    yaml = None\n",
    "\n",
    "try:\n",
    "    import pandas as pd\n",
    "except Exception:\n",
    "    pd = None\n",
    "\n",
    "try:\n",
    "    from bs4 import BeautifulSoup\n",
    "except Exception:\n",
    "    BeautifulSoup = None\n",
    "\n",
    "# 简单类型映射与启发式\n",
    "EXT_MAP = {\n",
    "    '.pdf': 'pdf',\n",
    "    '.docx': 'docx',\n",
    "    '.csv': 'csv',\n",
    "    '.xlsx': 'xlsx',\n",
    "    '.json': 'json',\n",
    "    '.yaml': 'yaml',\n",
    "    '.yml': 'yaml',\n",
    "    '.md': 'markdown',\n",
    "    '.markdown': 'markdown',\n",
    "    '.html': 'html',\n",
    "    '.htm': 'html',\n",
    "    '.txt': 'txt'\n",
    "}\n",
    "\n",
    "def detect_document_type(file_path: Optional[str] = None, content: Optional[str] = None) -> str:\n",
    "    \"\"\"返回 pdf|docx|csv|xlsx|json|yaml|html|markdown|txt 之一。\"\"\"\n",
    "    if file_path:\n",
    "        ext = os.path.splitext(file_path)[1].lower()\n",
    "        if ext in EXT_MAP:\n",
    "            return EXT_MAP[ext]\n",
    "    # 内容启发式\n",
    "    if content:\n",
    "        low = content.strip().lower()\n",
    "        if low.startswith('{') or low.startswith('['):\n",
    "            try:\n",
    "                json.loads(content)\n",
    "                return 'json'\n",
    "            except Exception:\n",
    "                pass\n",
    "        if low.startswith('---') and (yaml is not None):\n",
    "            # 可能是YAML或带元数据的Markdown\n",
    "            try:\n",
    "                _ = yaml.safe_load(content)\n",
    "                return 'yaml'\n",
    "            except Exception:\n",
    "                pass\n",
    "        if '<html' in low and BeautifulSoup is not None:\n",
    "            return 'html'\n",
    "        if re.search(r'^#\\\\s+|\\\\[.*?\\\\]\\\\(.*?\\\\)', content, re.M):\n",
    "            return 'markdown'\n",
    "        return 'txt'\n",
    "    return 'txt'\n",
    "\n",
    "print('detect_document_type 函数已加载。')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9870d71",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 各类型解析策略（必要库缺失时降级为简单文本返回）\n",
    "from io import BytesIO\n",
    "\n",
    "def parse_pdf(file_bytes: bytes) -> str:\n",
    "    try:\n",
    "        import PyPDF2\n",
    "        reader = PyPDF2.PdfReader(BytesIO(file_bytes))\n",
    "        return '\\n'.join(page.extract_text() or '' for page in reader.pages)\n",
    "    except Exception as e:\n",
    "        return f\"[PDF解析降级] {e}\"\n",
    "\n",
    "\n",
    "def parse_docx(file_bytes: bytes) -> str:\n",
    "    try:\n",
    "        import docx\n",
    "        f = BytesIO(file_bytes)\n",
    "        document = docx.Document(f)\n",
    "        return '\\n'.join(p.text for p in document.paragraphs)\n",
    "    except Exception as e:\n",
    "        return f\"[DOCX解析降级] {e}\"\n",
    "\n",
    "\n",
    "def parse_csv(file_bytes: bytes) -> str:\n",
    "    if pd is None:\n",
    "        return \"[CSV解析降级] pandas未安装\"\n",
    "    try:\n",
    "        f = BytesIO(file_bytes)\n",
    "        df = pd.read_csv(f)\n",
    "        return df.to_csv(index=False)\n",
    "    except Exception as e:\n",
    "        return f\"[CSV解析错误] {e}\"\n",
    "\n",
    "\n",
    "def parse_xlsx(file_bytes: bytes) -> str:\n",
    "    if pd is None:\n",
    "        return \"[XLSX解析降级] pandas未安装\"\n",
    "    try:\n",
    "        f = BytesIO(file_bytes)\n",
    "        df = pd.read_excel(f)\n",
    "        return df.to_csv(index=False)\n",
    "    except Exception as e:\n",
    "        return f\"[XLSX解析错误] {e}\"\n",
    "\n",
    "\n",
    "def parse_json(content: str) -> str:\n",
    "    try:\n",
    "        obj = json.loads(content)\n",
    "        return json.dumps(obj, ensure_ascii=False, indent=2)\n",
    "    except Exception as e:\n",
    "        return f\"[JSON解析错误] {e}\"\n",
    "\n",
    "\n",
    "def parse_yaml(content: str) -> str:\n",
    "    if yaml is None:\n",
    "        return \"[YAML解析降级] PyYAML未安装\"\n",
    "    try:\n",
    "        obj = yaml.safe_load(content)\n",
    "        return json.dumps(obj, ensure_ascii=False, indent=2)\n",
    "    except Exception as e:\n",
    "        return f\"[YAML解析错误] {e}\"\n",
    "\n",
    "\n",
    "def parse_html(content: str) -> str:\n",
    "    if BeautifulSoup is None:\n",
    "        return \"[HTML解析降级] bs4未安装\"\n",
    "    try:\n",
    "        soup = BeautifulSoup(content, 'html.parser')\n",
    "        # 提取可见文本\n",
    "        texts = [t.strip() for t in soup.stripped_strings]\n",
    "        return '\\n'.join(texts)\n",
    "    except Exception as e:\n",
    "        return f\"[HTML解析错误] {e}\"\n",
    "\n",
    "\n",
    "def parse_markdown(content: str) -> str:\n",
    "    # 简单去除markdown语法符号\n",
    "    cleaned = re.sub(r'[`*_>#-]+', '', content)\n",
    "    cleaned = re.sub(r'!\\[[^\\]]*\\]\\([^\\)]*\\)', '', cleaned)  # 去除图片\n",
    "    cleaned = re.sub(r'\\[[^\\]]*\\]\\([^\\)]*\\)', '', cleaned)  # 链接文本\n",
    "    return cleaned\n",
    "\n",
    "\n",
    "def parse_txt(content: str) -> str:\n",
    "    return content\n",
    "\n",
    "\n",
    "def parse_auto(doc_type: str, file_bytes: Optional[bytes] = None, content: Optional[str] = None) -> str:\n",
    "    if doc_type in ['pdf', 'docx', 'csv', 'xlsx'] and file_bytes is None:\n",
    "        return f\"[{doc_type}解析需要文件字节]\"\n",
    "    if doc_type == 'pdf':\n",
    "        return parse_pdf(file_bytes)\n",
    "    if doc_type == 'docx':\n",
    "        return parse_docx(file_bytes)\n",
    "    if doc_type == 'csv':\n",
    "        return parse_csv(file_bytes)\n",
    "    if doc_type == 'xlsx':\n",
    "        return parse_xlsx(file_bytes)\n",
    "    if doc_type == 'json':\n",
    "        return parse_json(content or '')\n",
    "    if doc_type == 'yaml':\n",
    "        return parse_yaml(content or '')\n",
    "    if doc_type == 'html':\n",
    "        return parse_html(content or '')\n",
    "    if doc_type == 'markdown':\n",
    "        return parse_markdown(content or '')\n",
    "    return parse_txt(content or '')\n",
    "\n",
    "print('解析策略函数已加载。')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b6e918c",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 关键字段抽取：LLM + 规则回退\n",
    "from datetime import datetime\n",
    "\n",
    "FIELD_SCHEMA_HINT = {\n",
    "    \"project_name\": \"string\",\n",
    "    \"owner\": \"string\",\n",
    "    \"budget\": {\"amount\": \"number\", \"currency\": \"string\"},\n",
    "    \"start_date\": \"YYYY-MM-DD\",\n",
    "    \"end_date\": \"YYYY-MM-DD\"\n",
    "}\n",
    "\n",
    "EXTRACT_PROMPT = (\n",
    "    \"请从下列文本中抽取关键项目字段并返回JSON。只返回JSON，不要多余说明。\\n\"\n",
    "    \"字段: project_name, owner, budget.amount, budget.currency, start_date, end_date。\\n\"\n",
    "    \"日期格式: YYYY-MM-DD, 金额为数字, 缺失用 null。\\n文本:\\n\" \n",
    ")\n",
    "\n",
    "import json as _json\n",
    "\n",
    "def extract_key_fields_via_llm(text: str) -> dict:\n",
    "    messages = [\n",
    "        {\"role\": \"system\", \"content\": \"你是一个信息抽取助手，只输出有效JSON。\"},\n",
    "        {\"role\": \"user\", \"content\": EXTRACT_PROMPT + text}\n",
    "    ]\n",
    "    try:\n",
    "        resp = openai.ChatCompletion.create(\n",
    "            model=\"gpt-3.5-turbo\",\n",
    "            messages=messages,\n",
    "            max_tokens=256,\n",
    "            temperature=0\n",
    "        )\n",
    "        raw = resp.choices[0].message.content.strip()\n",
    "        # 尝试处理可能的代码块\n",
    "        m = re.search(r\"```(?:json)?\\s*(\\{[\\s\\S]*?\\})\\s*```\", raw)\n",
    "        if m:\n",
    "            raw = m.group(1)\n",
    "        return _json.loads(raw)\n",
    "    except Exception:\n",
    "        return {}\n",
    "\n",
    "# 规则/正则回退（中文示例）\n",
    "RE_PROJECT = re.compile(r\"项目名称[:：]\\s*([\\w\\-\\u4e00-\\u9fa5 ]+)\")\n",
    "RE_OWNER = re.compile(r\"负责人[:：]\\s*([\\w\\-\\u4e00-\\u9fa5 ]+)\")\n",
    "RE_BUDGET = re.compile(r\"预算[:：]\\s*([0-9,.]+)\\s*([A-Za-z\\u4e00-\\u9fa5¥￥$€]*)\")\n",
    "RE_DATE = re.compile(r\"(\\d{4}[年\\-/]?(\\d{1,2})[月\\-/]?(\\d{1,2})日?)\")\n",
    "\n",
    "CURRENCY_MAP = {\n",
    "    '¥': 'CNY', '￥': 'CNY', '人民币': 'CNY', 'CNY': 'CNY',\n",
    "    '$': 'USD', 'USD': 'USD', '美元': 'USD',\n",
    "    '€': 'EUR', 'EUR': 'EUR', '欧元': 'EUR'\n",
    "}\n",
    "\n",
    "\n",
    "def extract_key_fields(text: str) -> dict:\n",
    "    data = extract_key_fields_via_llm(text) or {}\n",
    "    # 规则兼容/补全\n",
    "    if not data.get('project_name'):\n",
    "        m = RE_PROJECT.search(text)\n",
    "        if m: data['project_name'] = m.group(1).strip()\n",
    "    if not data.get('owner'):\n",
    "        m = RE_OWNER.search(text)\n",
    "        if m: data['owner'] = m.group(1).strip()\n",
    "    if not data.get('budget') or not isinstance(data.get('budget'), dict):\n",
    "        data['budget'] = data.get('budget') or {}\n",
    "    if not data['budget'].get('amount'):\n",
    "        m = RE_BUDGET.search(text)\n",
    "        if m:\n",
    "            amt = m.group(1).replace(',', '')\n",
    "            data['budget']['amount'] = float(amt)\n",
    "            cur = m.group(2).strip() if m.group(2) else ''\n",
    "            data['budget']['currency'] = CURRENCY_MAP.get(cur, cur or 'CNY')\n",
    "    if not data['budget'].get('currency'):\n",
    "        data['budget']['currency'] = 'CNY'\n",
    "\n",
    "    # 日期简单提取（取前两个匹配分别作为起止）\n",
    "    if not data.get('start_date') or not data.get('end_date'):\n",
    "        dates = []\n",
    "        for mt in RE_DATE.finditer(text):\n",
    "            ymd = re.sub(r\"[年/月]\", '-', mt.group(1))\n",
    "            ymd = re.sub(r\"日\", '', ymd)\n",
    "            # 标准化yyyy-mm-dd\n",
    "            parts = re.split(r\"[-/]\", ymd)\n",
    "            if len(parts) >= 3:\n",
    "                y, m, d = parts[0], parts[1].zfill(2), parts[2].zfill(2)\n",
    "                dates.append(f\"{y}-{m}-{d}\")\n",
    "        if dates:\n",
    "            if not data.get('start_date'):\n",
    "                data['start_date'] = dates[0]\n",
    "            if not data.get('end_date') and len(dates) > 1:\n",
    "                data['end_date'] = dates[1]\n",
    "    return data\n",
    "\n",
    "print('字段抽取函数已加载。')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99ea9790",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 质量验证与清洗\n",
    "from dateutil import parser as dateparser # 占位，使用简单解析以避免额外依赖\n",
    "\n",
    "VALID_CURRENCIES = {\"CNY\", \"USD\", \"EUR\"}\n",
    "\n",
    "def to_iso_date(s: str) -> str:\n",
    "    try:\n",
    "        # 简单split解析\n",
    "        parts = re.split(r\"[-/]\", s)\n",
    "        if len(parts) >= 3:\n",
    "            y, m, d = parts[0], parts[1].zfill(2), parts[2].zfill(2)\n",
    "            return f\"{y}-{m}-{d}\"\n",
    "    except Exception:\n",
    "        pass\n",
    "    return s\n",
    "\n",
    "\n",
    "def validate_and_clean(fields: dict) -> dict:\n",
    "    out = {\n",
    "        \"project_name\": None,\n",
    "        \"owner\": None,\n",
    "        \"budget\": {\"amount\": None, \"currency\": None},\n",
    "        \"start_date\": None,\n",
    "        \"end_date\": None,\n",
    "        \"issues\": []\n",
    "    }\n",
    "    if not fields:\n",
    "        out[\"issues\"].append(\"empty_fields\")\n",
    "        return out\n",
    "\n",
    "    # 文本清理\n",
    "    pn = (fields.get('project_name') or '').strip() or None\n",
    "    ow = (fields.get('owner') or '').strip() or None\n",
    "\n",
    "    # 预算\n",
    "    bd = fields.get('budget') or {}\n",
    "    amt = bd.get('amount')\n",
    "    cur = (bd.get('currency') or '').strip().upper() or 'CNY'\n",
    "    try:\n",
    "        amt = float(amt) if amt is not None else None\n",
    "    except Exception:\n",
    "        out['issues'].append('budget_amount_invalid')\n",
    "        amt = None\n",
    "    if cur not in VALID_CURRENCIES:\n",
    "        out['issues'].append('currency_normalized')\n",
    "        # 简单归一\n",
    "        cur = CURRENCY_MAP.get(cur, 'CNY')\n",
    "\n",
    "    # 日期\n",
    "    sd = fields.get('start_date') or None\n",
    "    ed = fields.get('end_date') or None\n",
    "    if sd: sd = to_iso_date(sd)\n",
    "    if ed: ed = to_iso_date(ed)\n",
    "    if sd and ed and sd > ed:\n",
    "        out['issues'].append('start_after_end_swapped')\n",
    "        sd, ed = ed, sd\n",
    "\n",
    "    out.update({\n",
    "        'project_name': pn,\n",
    "        'owner': ow,\n",
    "        'budget': {'amount': amt, 'currency': cur},\n",
    "        'start_date': sd,\n",
    "        'end_date': ed\n",
    "    })\n",
    "\n",
    "    # 缺失项提示\n",
    "    for k in ['project_name','owner','start_date','end_date']:\n",
    "        if out.get(k) is None:\n",
    "            out['issues'].append(f'missing_{k}')\n",
    "    if out['budget']['amount'] is None:\n",
    "        out['issues'].append('missing_budget_amount')\n",
    "    return out\n",
    "\n",
    "print('质量验证与清洗函数已加载。')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6462ae1a",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 结构化特征向量化\n",
    "try:\n",
    "    from sklearn.feature_extraction import DictVectorizer\n",
    "except Exception:\n",
    "    DictVectorizer = None\n",
    "\n",
    "\n",
    "def vectorize_features(cleaned: dict):\n",
    "    if DictVectorizer is None:\n",
    "        return None, ['sklearn未安装，无法向量化']\n",
    "    flat = {\n",
    "        'project_name': cleaned.get('project_name') or '',\n",
    "        'owner': cleaned.get('owner') or '',\n",
    "        'budget_amount': cleaned.get('budget', {}).get('amount') or 0.0,\n",
    "        'budget_currency': cleaned.get('budget', {}).get('currency') or 'CNY',\n",
    "        'start_date': cleaned.get('start_date') or '',\n",
    "        'end_date': cleaned.get('end_date') or ''\n",
    "    }\n",
    "    # 简单日期差特征\n",
    "    if flat['start_date'] and flat['end_date'] and len(flat['start_date'])==10 and len(flat['end_date'])==10:\n",
    "        try:\n",
    "            y1,m1,d1 = map(int, flat['start_date'].split('-'))\n",
    "            y2,m2,d2 = map(int, flat['end_date'].split('-'))\n",
    "            duration = (y2 - y1)*365 + (m2 - m1)*30 + (d2 - d1)\n",
    "        except Exception:\n",
    "            duration = 0\n",
    "    else:\n",
    "        duration = 0\n",
    "    flat['duration_days_est'] = duration\n",
    "\n",
    "    dv = DictVectorizer(sparse=False)\n",
    "    vec = dv.fit_transform([flat])[0]\n",
    "    return dv.get_feature_names_out(), vec\n",
    "\n",
    "print('向量化函数已加载。')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8473ed33",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 示例：端到端感知增强流程（使用文本样例）\n",
    "sample_text = (\n",
    "    \"项目名称：智慧园区升级项目\\n\"\n",
    "    \"负责人：王强\\n\"\n",
    "    \"预算：1,200,000 人民币\\n\"\n",
    "    \"起止时间：2025-01-15 至 2025-06-30\\n\"\n",
    "    \"项目目标：部署统一物联网平台，优化能耗与安防。\\n\"\n",
    ")\n",
    "\n",
    "# 1) 自动识别类型\n",
    "sample_type = detect_document_type(content=sample_text)\n",
    "print('识别类型:', sample_type)\n",
    "\n",
    "# 2) 解析（文本样例直接使用）\n",
    "parsed_text = parse_auto(sample_type, content=sample_text)\n",
    "print('\\n解析文本预览:\\n', parsed_text[:200])\n",
    "\n",
    "# 3) 关键字段抽取\n",
    "fields = extract_key_fields(parsed_text)\n",
    "print('\\n抽取字段:', fields)\n",
    "\n",
    "# 4) 质量验证与清洗\n",
    "cleaned = validate_and_clean(fields)\n",
    "print('\\n清洗结果:', cleaned)\n",
    "\n",
    "# 5) 向量化\n",
    "feat_names, vec = vectorize_features(cleaned)\n",
    "print('\\n特征名称:', feat_names)\n",
    "print('向量:', vec)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c4bb32e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 检索：根据用户输入检索相关知识\n",
    "# 这里模拟检索过程，可替换为实际的知识库或API调用\n",
    "retrieved_knowledge = \"Transformer是一种基于自注意力机制（Self-Attention）的深度学习模型架构，能够并行处理序列数据，广泛应用于自然语言处理等任务。\"\n",
    "print(\"检索到的知识：\", retrieved_knowledge)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "985fb98a",
   "metadata": {},
   "source": [
    "## 3. 推理（Reasoning）\n",
    "\n",
    "Agent结合用户输入和检索到的知识，进行推理和分析，形成初步答案。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0a40b744",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 推理：结合输入和检索知识进行分析\n",
    "reasoning_result = f\"用户问题：{user_input}\\n相关知识：{retrieved_knowledge}\\n\\n推理：Transformer架构的核心思想是利用自注意力机制实现序列中各元素间的全局依赖建模，提升了并行计算能力和长距离依赖建模能力。\"\n",
    "print(reasoning_result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9dde614e",
   "metadata": {},
   "source": [
    "## 4. 生成（Generation）\n",
    "\n",
    "Agent根据推理结果生成自然语言回答。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8afa6901",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 生成：将推理结果转为自然语言回答\n",
    "final_answer = \"Transformer是一种基于自注意力机制的深度学习模型架构，能够高效建模序列中各元素间的全局依赖，提升并行计算和长距离依赖建模能力。\"\n",
    "print(\"Agent生成的回答：\", final_answer)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ef93181",
   "metadata": {},
   "source": [
    "## 5. 反馈（Feedback）\n",
    "\n",
    "用户对Agent的回答进行评价，Agent可根据反馈调整后续行为。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88d4619d",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 反馈：用户对Agent回答进行评价\n",
    "user_feedback = \"回答准确，表达清晰。\"\n",
    "print(\"用户反馈：\", user_feedback)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1cf25d91",
   "metadata": {},
   "source": [
    "## 6. 自驱优化（Self-Improvement）\n",
    "\n",
    "Agent根据用户反馈，优化自身知识库或推理、生成策略，实现自我提升。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7cb83922",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 自驱优化：根据反馈调整知识或策略（示例为简单记录反馈）\n",
    "# 实际应用中可将反馈用于微调模型、更新知识库等\n",
    "agent_memory = []\n",
    "def self_improve(feedback, memory):\n",
    "    memory.append(feedback)\n",
    "    print(\"Agent已记录反馈，用于后续优化。\")\n",
    "\n",
    "self_improve(user_feedback, agent_memory)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "base",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
